//查看绩效基本数据 
//新建调整单
//查看调整单
//绩效调整申请单


public without sharing class SalesPerformanceDataSheetController {
    public Boolean isErr {private set;get;}
    public String  backId {private set;get;}
    public String msg {private set;get;}
    public Boolean isSuccess {private set; get;}

    public String dataJson {private set;get;}
    public String saveJson { set;get;}
    public String searchJson { set; get;}
    public String userId {get;private set;}
    public Boolean canEdit {get;private set;}

    private User u ;
    private Boolean isNew;
    private Map<String,DataUtil.SObjectBean> stageObjectMap;
   	private SalesPerformanceAdjustment__c sps  ;

   	public SalesPerformanceDataSheetController (ApexPages.StandardController stdController){
   		backId = System.currentPageReference().getParameters().get('id');
        u = [select Id,Name,ExuserCode__c from User where Id =:UserInfo.getUserId()];
        sps = new SalesPerformanceAdjustment__c();
        isNew = false;
        stageObjectMap = new Map<String,DataUtil.SObjectBean> ();
   	}

    public SalesPerformanceDataSheetController() {
        backId = System.currentPageReference().getParameters().get('id');
        u = [select Id,Name,ExuserCode__c from User where Id =:UserInfo.getUserId()];
        sps = new SalesPerformanceAdjustment__c();
        isNew = false;
        stageObjectMap = new Map<String,DataUtil.SObjectBean> ();
    }


    private Map<String,Object> getConfigMap(){
            List<StaticResource> srs = [select Body from StaticResource  where name = 'SalesPerformanceDataSheet' limit 1 ];
    	//String config = '{"ReagentPerformance":{"rtype":"ReagentBudgetAdjust","onlyKeys":["Company__c","AccountPK__c","TerminalAccountPK__c","ReagentCategory__c"]},"InstrumentPerformance":{"rtype":"InstrumentPerformanceAdjust","onlyKeys":["Company__c","AccountPK__c","TerminalAccountPK__c","InstrumentClasses__c"]},"ReagentIncrementalPerformance":{"rtype":"ReagentIncrementalPerformanceAdjust","onlyKeys":["Company__c","AccountPK__c","TerminalAccountPK__c","Category__c"]},"AnnualIncrementPerformance":{"rtype":"AnnualIncrementPerformanceAdjust","onlyKeys":["Company__c","AccountPK__c","TerminalAccountPK__c","ReagentCategory__c"]},"AgentIncrementPerformance":{"rtype":"AgentIncrementPerformanceAdjust","onlyKeys":["Company__c","AccountPK__c","TerminalAccountPK__c","ReagentCategory__c"]}}';
		return (Map<String,Object> ) JSON.deserializeUntyped(srs[0].Body.toString());
    }
    public void  initDetails(){

		Map<String,Object> dataMap = new Map<String,Object>();
		dataMap.put('year', getYear());
		dataMap.put('quater', getQuater());
		Map<String,String> types = new Map<String,String>();
		types.put('ReagentPerformance', '试剂绩效基础数据');
		types.put('InstrumentPerformance', '仪器绩效基础数据');
		types.put('ReagentIncrementalPerformance', '试剂增量绩效基础数据');
		types.put('AnnualIncrementPerformance', '年度试剂增量绩效基础数据');
		types.put('AgentIncrementPerformance', '代理试剂增量绩效基础数据');
		dataMap.put('type', types);
		dataMap.put('combobox',getCombox('SalesPerformanceDataSheet__c',new Set<String>{'Company__c'}));
       	dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap ),'UTF-8');
       	userId = Userinfo.getUserId();

    }

     
    public void save(){
    	msg = '';
    	try {
    	  	
    		Map<String,Object>saveMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
	        Map<String,Set<String>> fieldsMap = getFields();
	        Map<String,DataUtil.FieldBean> fbeanMap = DataUtil.getFieldsInfo(SalesPerformanceAdjustment__c.SObjecttype,fieldsMap.get('SalesPerformanceAdjustment__c'));


	            Map<String,Object> obj = (Map<String,Object>) saveMap.get('base');

	            for (String field :  obj.keySet()) {

	                if(obj.get(field) == null || DataUtil.getStringValue(obj.get(field)) == '') continue;

	                if(fbeanMap.containsKey(field) )sps.put(field, DataUtil.dataHandler(obj.get(field),fbeanMap.get(field).type.toUpperCase() ));

	            }
	        Map<String,Object>  detailMap  = ( Map<String,Object>) saveMap.get('details');

	        
	        List<SalesPerformanceDataSheet__c>spList = new List<SalesPerformanceDataSheet__c>();
	        Set<String> exsets = new Set<String>();
	        
	        Map<String ,Object> configMap = getConfigMap();
	        Map<String,String> recordMap = new Map<String,String>();
	        for(String rtype: configMap.keySet()){

	        	recordMap.put(rtype, Utils.getRecordTypeIdByDevNameAndObjName( (String)((Map<String,Object>)configMap.get(rtype)).get('rtype'), 'SalesPerformanceDataSheet__c'));
	        }
	    	User worker = [select Id,EmployeeNumber from User where Id=:sps.User__c ];

	       // Map<String,String>quaterMap = ImportObject.getPicklistValues('SalesPerformanceAdjustment__c', 'Quarter__c', true);

	        for(String rtype : detailMap.keySet()){
	        	List<Object>  saveList = (List<Object> )detailMap.get(rtype);
	        	for(Object o : saveList){
	        		Map<String,Object> mo = (Map<String,Object>)o;

	        		SalesPerformanceDataSheet__c sp = new SalesPerformanceDataSheet__c();
		        	sp.RecordTypeId = recordMap.get(rtype);

		        	sp.Year__c = sps.Year__c;
		        	sp.Quarter__c = sps.Quarter__c;
		        	sp.EmployeeNumber__c = worker.EmployeeNumber;
		        	sp.Name__c = DataUtil.getStringValue(mo.get('name'));
		        	String detailId = DataUtil.getStringValue(mo.get('detailId'));
		        	Boolean detailIsEmpty = String.isBlank(detailId);
		        	if(!detailIsEmpty)sp.Id = detailId;
		        	if(!detailIsEmpty) exsets.add(detailId);
		        	if(detailIsEmpty)sp.SalesPerformanceDataSheet__c = DataUtil.getStringValue(mo.get('relatedId'));
		        	sp.Company__c = DataUtil.getStringValue(mo.get('company'));
		        	sp.Province__c = DataUtil.getStringValue(mo.get('province'));
		        	sp.AccountPK__c = DataUtil.getStringValue(mo.get('accpk'));
		        	sp.Account__c = DataUtil.getStringValue(mo.get('accId'));
		        	sp.TerminalAccount__c = DataUtil.getStringValue(mo.get('terminalId'));
		        	sp.TerminalAccountPK__c = DataUtil.getStringValue(mo.get('terminalpk'));
		        	sp.JobCategory__c = DataUtil.getStringValue(mo.get('jobclass'));

		    		sp.BudgetQuantityQ1__c =  DataUtil.getDecimalValue(mo.get('tn1'));
		    		sp.BudgetQuantityQ2__c =  DataUtil.getDecimalValue(mo.get('tn2'));
		    		sp.BudgetQuantityQ3__c =  DataUtil.getDecimalValue(mo.get('tn3'));
		    		sp.BudgetQuantityQ4__c =  DataUtil.getDecimalValue(mo.get('tn4'));

		    		//sp.BudgetQuantity__c = DataUtil.getDecimalValue(mo.get('countTn'));

		    		sp.ActualQuantityQ1__c =  DataUtil.getDecimalValue(mo.get('an1'));
		    		sp.ActualQuantityQ2__c =  DataUtil.getDecimalValue(mo.get('an2'));
		    		sp.ActualQuantityQ3__c =  DataUtil.getDecimalValue(mo.get('an3'));
		    		sp.ActualQuantityQ4__c =  DataUtil.getDecimalValue(mo.get('an4'));

		    		//sp.ActualQuantity__c = DataUtil.getDecimalValue(mo.get('countAn'));

		    		sp.LastYearSalesVolumeQ1__c =  DataUtil.getDecimalValue(mo.get('ls1'));
		    		sp.LastYearSalesVolumeQ2__c =  DataUtil.getDecimalValue(mo.get('ls2'));
		    		sp.LastYearSalesVolumeQ3__c =  DataUtil.getDecimalValue(mo.get('ls3'));
		    		sp.LastYearSalesVolumeQ4__c =  DataUtil.getDecimalValue(mo.get('ls4'));
		    		
		    		if(rtype == 'AgentIncrementPerformance' || rtype == 'AnnualIncrementPerformance' )sp.LastYearSalesVolume__c = DataUtil.getDecimalValue(mo.get('countLs'));

		    		sp.BudgetSalesQ1__c =  DataUtil.getDecimalValue(mo.get('ts1'));
		    		sp.BudgetSalesQ2__c =  DataUtil.getDecimalValue(mo.get('ts2'));
		    		sp.BudgetSalesQ3__c =  DataUtil.getDecimalValue(mo.get('ts3'));
		    		sp.BudgetSalesQ4__c =  DataUtil.getDecimalValue(mo.get('ts4'));

		    		//sp.BudgetSales__c = DataUtil.getDecimalValue(mo.get('countTs'));

		    		sp.ActualSalesQ1__c =  DataUtil.getDecimalValue(mo.get('as1'));
		    		sp.ActualSalesQ2__c =  DataUtil.getDecimalValue(mo.get('as2'));
		    		sp.ActualSalesQ3__c =  DataUtil.getDecimalValue(mo.get('as3'));
		    		sp.ActualSalesQ4__c =  DataUtil.getDecimalValue(mo.get('as4'));
		    		sp.SalesMarket__c = DataUtil.getStringValue(mo.get('saleMarket'));
		    		

		    		if(rtype == 'AgentIncrementPerformance' || rtype == 'AnnualIncrementPerformance' )sp.ActualSales__c = DataUtil.getDecimalValue(mo.get('countAs'));
		    		sp.Reason__c =  DataUtil.getStringValue(mo.get('reason'));

		    		sp.Category__c = DataUtil.getStringValue(mo.get('cate')); 
		    		sp.InstrumentClasses__c = DataUtil.getStringValue(mo.get('equipCate')); 
		    		sp.ReagentCategory__c = DataUtil.getStringValue(mo.get('regentCate')); 

		    		sp.NotActive__c = true;
		        	spList.add(sp);
	        	} 
	        	
	        }

	        Savepoint sp = Database.setSavepoint();
	        try {
	            
	            System.debug(sps);
	            upsert sps;
	            delete [select Id from SalesPerformanceDataSheet__c where SalesPerformanceAdjustment__c =:sps.Id and  Id not in:exsets];

	            for (SalesPerformanceDataSheet__c spds  :spList ) {
	            	spds.SalesPerformanceAdjustment__c = sps.Id;
	            }
	           	if(!spList.isEmpty())upsert spList;
	           	isSuccess = true;
	           	backId = sps.Id;
	           	msg = '保存成功!';
	        }
	        catch (Exception e) {
	        	if(isNew)sps.Id = null;
    	    	msg = '保存失败:'+e.getMessage()+e.getStackTraceString();
    	    	Database.rollback(sp);
	        }
	        

    	}
    	catch (Exception e) {
    	    msg = '保存失败:'+e.getMessage();

    	}
    	System.debug(msg);
    	
    }
    private String getYear(){

    	if(System.today().Month() <=3 ) return (System.today().year()-1)+'年';
    	return (System.today().year())+'年';
    }
    private String getQuater(){
    	if(System.today().Month() <=3 ) return '4';
    	if(System.today().Month() <= 6) return '1';
    	if(System.today().Month() <= 9) return '2';
    	if(System.today().Month() <= 12) return '3';
    	return '1';
    }

    public void init(){

    	canEdit = true;
    	try {

    	    if(backId !=null  && Id.valueOf(backId).getSObjectType() == SalesPerformanceAdjustment__c.sObjectType){
    	    	isNew = false;
    	    	sps = [select Id,User__c,Status__c,Year__c,Quarter__c, User__r.ExuserCode__c  from SalesPerformanceAdjustment__c where Id=:backId];
    	    	if(sps.Status__c == '审批中' || sps.Status__c == '审批成功' ) canEdit = false;//throw new DmlException('销售绩效结果调整单'+sps.Status__c +',不能修改!' );


    	    }else{

    	    	sps = new SalesPerformanceAdjustment__c();
    	    	sps.Status__c = '草案中';
    	    	sps.User__c = u.Id;
    	    	sps.Year__c = getYear();
    	    	sps.Quarter__c = getQuater();
    	    	isNew = true;
    	    	//List<SalesPerformanceAdjustment__c> sp = [select Id,Name  from SalesPerformanceAdjustment__c where User__c =:sps.User__c and Year__c=:sps.Year__c  and Quarter__c=:sps.Quarter__c ]
    	    	//if(>0)throw new DmlException('已经存在绩效调整申请:');
    	    }


   		    Map<String,Object> dataMap = new Map<String,Object>();
			dataMap.put('combobox',getCombox('SalesPerformanceDataSheet__c',new Set<String>{'Company__c'}));
    	    dataMap.put('detail', getDetails());
              //字段
             Map<String,Set<String>> fieldsmap = getFields();
             //字段详情
             Map<String, List<DataUtil.FieldBean>> fbMap = DataUtil.getFieldsBean(fieldsmap,stageObjectMap);
            
            //字段赋值
             Map<String,List<DataUtil.FieldBean>> fields = DataUtil.setFieldsValue(fbMap,DataUtil.getBaseInfo(fbMap,stageObjectMap) );
           	
            if(isNew){

            	for (DataUtil.FieldBean fb   :  fields.get('SalesPerformanceAdjustment__c')) {
	                Map<String,Object> vMap  = new Map<String,Object>();
	                if(fb.name == 'User__c'){

	                    vMap.put('Id', u.Id );
	                    vMap.put('Name', u.Name );
	                    fb.value = vMap;
	                }	              

	                if(fb.name == 'Year__c')fb.value = sps.Year__c ;

	                if(fb.name == 'Quarter__c')fb.value = sps.Quarter__c;

	            }

            }
           	
            dataMap.put('base',fields);
            dataMap.put('baseObject',DataUtil.getBaseObjectMap(stageObjectMap)); 
            dataMap.put('detail',getDetails());
        	dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap ),'UTF-8');

    	}
    	catch (Exception e) {
    	    isErr = true ;
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()+e.getStackTraceString()));
    	}
    	
    }


    private Map<String ,Map<String,String>> getCombox(String objName ,Set<String> fields ){
    	Map<String ,Map<String,String>> tmp = new Map<String ,Map<String,String>>();
    	for(String f : fields){
    		Map<String,String> pickMap = ImportObject.getPicklistValues(objName, f, true);
    		tmp.put(f, pickMap);
    	}
    	return tmp;
    } 

   
   
   	private Map<String,Set<String>>  getFields(){
   		Map<String,Set<String>> fieldsMap  = new  Map<String,Set<String>>();
        
            DataUtil.SObjectBean sb = new DataUtil.SObjectBean();

            sb.title ='';
            sb.objname = 'SalesPerformanceAdjustment__c';
            sb.stype = DataUtil.getSObjectType(sb.objname );
            if(!isNew)sb.idvalue = backId;
            sb.type = 'base';
            // System.debug(sb);
            //   System.debug(isNew);
            //   System.debug(' xxx'+backId);
            if(!isNew)sb.condition = ' where Id =\''+backId +'\'';
            stageObjectMap.put(sb.objname ,sb );
            Set<String>  fields = new Set<String>{'Year__c','Quarter__c','User__c'};
         
            fieldsMap.put(sb.objname , fields);
        
        return fieldsMap;
   	}

   	public void searchDetail(){

   			Map<String,Object>searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));

    	
	    	Schema.DescribeSobjectResult m = SalesPerformanceDataSheet__c.sObjectType.getDescribe();
	        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

	        String sql = 'select ';
	        List<String> fields = new List<String>();
	        for (String field : fieldMap.keySet()) {
	             fields.add(field);
	        }
	        sql += String.join(fields, ',');

	    	sql += ', RecordType.DeveloperName ,TerminalAccount__r.Name,Account__r.Name  from SalesPerformanceDataSheet__c where  NotActive__c = false    ';
	    	Map<String,Object> configMap = getConfigMap();

	    	String rtype = DataUtil.getStringValue(searchMap.get('rtype'));
	    	if(!String.isBlank(rtype))sql += ' and  ( RecordType.DeveloperName  =\''+rtype +'\'   ';
	    	if(String.isBlank(rtype))throw new DmlException('请选择需要查询的基础数据类型') ;

	    	if(!configMap.containsKey(rtype))throw new DmlException('请联系管理员维护对应的调整数据类型!静态资源:SalesPerformanceDataSheet') ;
	    	String adjustType =  (String)((Map<String,Object>)configMap.get(rtype)).get('rtype');
	    	sql += ' or RecordType.DeveloperName  =\''+adjustType +'\'    )  ';


	    	String workno = DataUtil.getStringValue(searchMap.get('workno'));
	    	if(String.isBlank(workno))throw new DmlException('请选择需调整绩效用户') ;

	    	List<User> workers = [select Id ,EmployeeNumber ,ExuserCode__c from User where Id=:workno];
	    	if(workers.isEmpty())throw new DmlException('请选择需调整绩效用户') ;

	    	//if(!String.isBlank(workno))sql += ' and EmployeeNumber__c =\''+workers[0].EmployeeNumber +'\' ';
	    	sql += ' and EmployeeNumber__c =\''+workers[0].EmployeeNumber +'\' ';

	    	String quater = DataUtil.getStringValue(searchMap.get('quater'));
	    	if(!String.isBlank(quater))sql += ' and Quarter__c =\''+quater +'\' ';
	    	if(String.isBlank(quater))throw new DmlException('请选择季度!') ;

	    	String province = DataUtil.getStringValue(searchMap.get('province'));
	    	if(!String.isBlank(province))sql += ' and Province__c like\'%'+province +'%\' ';

	    	String year = DataUtil.getStringValue(searchMap.get('year'));
	    	if(!String.isBlank(year))sql += ' and Year__c =\''+year +'\' ';
	    	if(String.isBlank(year))throw new DmlException('请选择年度!') ;


	    	sql += ' Order by JobCategory__c , AccountPK__c, TerminalAccountPK__c ';

	    	List<PerformanceBean> tmp = new List<PerformanceBean>();
	    	System.debug('SalesPerformanceDataSheetController==>'+sql);
	    	for (SalesPerformanceDataSheet__c sp: Database.query(sql) ) {
	    		tmp.add( new  PerformanceBean(sp) );

	    	}
	    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

   	}


   


   
    public void search(){
    	msg = '';
    	try {
    		Map<String,Object>searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));

    	
	    	Schema.DescribeSobjectResult m = SalesPerformanceDataSheet__c.sObjectType.getDescribe();
	        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

	        String sql = 'select ';
	        List<String> fields = new List<String>();
	        for (String field : fieldMap.keySet()) {
	             fields.add(field);
	        }
	        sql += String.join(fields, ',');

	    	sql += ', RecordType.DeveloperName ,TerminalAccount__r.Name,Account__r.Name  from SalesPerformanceDataSheet__c where CreatedDate != null   ';

	    	String historysql = sql;

	    	String rtype = DataUtil.getStringValue(searchMap.get('rtype'));
	    	if(!String.isBlank(rtype))sql += ' and  RecordType.DeveloperName  =\''+rtype +'\' ';


	    	String workno = DataUtil.getStringValue(searchMap.get('workno'));
	    	if(String.isBlank(workno))throw new DmlException('请选择需调整绩效用户') ;

	    	List<User> workers = [select Id,ExuserCode__c,EmployeeNumber  from User where Id=:workno];
	    	
	    	if(workers.isEmpty())throw new DmlException('请选择需调整绩效用户') ;

	    	if(!String.isBlank(workno))sql += ' and EmployeeNumber__c =\''+workers[0].EmployeeNumber +'\' ';


	    	String quater = DataUtil.getStringValue(searchMap.get('quater'));
	    	if(!String.isBlank(quater))sql += ' and Quarter__c =\''+quater +'\' ';
	    	if(String.isBlank(quater))throw new DmlException('请选择季度!') ;

	    	String province = DataUtil.getStringValue(searchMap.get('province'));
	    	if(!String.isBlank(province))sql += ' and Province__c like\'%'+province +'%\' ';

	    	String year = DataUtil.getStringValue(searchMap.get('year'));
	    	if(!String.isBlank(year))sql += ' and Year__c =\''+year +'\' ';
	    	if(String.isBlank(year))throw new DmlException('请选择年度!') ;


	    	String company = DataUtil.getStringValue(searchMap.get('company'));
	    	if(!String.isBlank(company))sql += ' and Company__c =\''+company +'\' ';

	    	String accName  = DataUtil.getStringValue(searchMap.get('accName'));
	    	if(!String.isBlank(accName))sql += ' and (Account__r.Name  like \'%'+accName +'%\' or  AccountPK__c = \'%'+accName +'%\') ';
	    	
	    	String terminalName  = DataUtil.getStringValue(searchMap.get('terminalName'));
	    	if(!String.isBlank(terminalName))sql += ' and (TerminalAccount__r.Name  like \'%'+terminalName +'%\' or  TerminalAccountPK__c = \'%'+terminalName +'%\') ';
	    	List<PerformanceBean> tmp = new List<PerformanceBean>();

	    	System.debug(sql);

	    	Map<String,PerformanceBean> tmpMap  = new Map<String,PerformanceBean>();
	    	//NC
	    	for (SalesPerformanceDataSheet__c sp: Database.query(sql) ) {
	    		
	    		tmpMap.put(sp.Id , new  PerformanceBean(sp) );

	    	}

	    	historysql += ' and SalesPerformanceDataSheet__c in  (\''+String.join(new List<String>(tmpMap.keySet()), '\',\'')+'\')  and  SalesPerformanceAdjustment__r.Status__c =\'审批成功\' order by LastModifiedDate desc  ';
	    	
	    	System.debug(historysql);
		   // System.debug('search=>'+ tmpMap.keySet());

	    	if(!tmpMap.isEmpty()){

	    		//去检索历史调整记录
		    	for (SalesPerformanceDataSheet__c sp   :Database.query(historysql) ) {
		    			//sp.SalesPerformanceAdjustment__r.Status__c
		    		//	System.debug('search=>'+ sp.Id +' '+sp.SalesPerformanceDataSheet__c);
		    			PerformanceBean pb = tmpMap.get(sp.SalesPerformanceDataSheet__c );
		    			if(pb == null)continue;
						if(pb.historys != null && pb.historys.size() > 0 )continue;
		    			pb.historys =  pb.historys == null ? new List<PerformanceBean>() : pb.historys;
		    			pb.historys.add(new PerformanceBean(sp));

		    	}


	    	}
	    	
	    	
	    	if(tmpMap.values().isEmpty())msg = '没有数据!';
		   // System.debug('search=>'+ tmpMap.values());
	    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmpMap.values()), 'UTF-8');
    	    
    	}
    	catch (Exception e) {
    		msg = e.getMessage();
    		System.debug('SalesPerformanceDataSheetController==>'+e.getStackTraceString());
	    	dataJson = EncodingUtil.urlEncode('[]', 'UTF-8');

    	}
    	
    }

    public Map<String,List<PerformanceBean>> getDetails(){
    	
	    Map<String,List<PerformanceBean>> res = new Map<String,List<PerformanceBean>>();

     	if(isNew) return res;
     	Map<String,String>recordMap = new Map<String,String>();

     	Map<String,Object >configMap = getConfigMap();

     	for(String rtype: configMap.keySet()){

     		String  targetRt  = (String )((Map<String,Object>)configMap.get(rtype)).get('rtype');
	        recordMap.put(targetRt,rtype );
	    }

    	Schema.DescribeSobjectResult m = SalesPerformanceDataSheet__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

        String sql = 'select ';
        List<String> fields = new List<String>();
        for (String field : fieldMap.keySet()) {
             fields.add(field);
        }
        sql += String.join(fields, ',');

    	sql += ',TerminalAccount__r.Name,Account__r.Name, RecordType.DeveloperName from SalesPerformanceDataSheet__c ';

    	String historysql = sql ;
    	String ncsql = sql ;
    	sql += ' where SalesPerformanceAdjustment__c =\''+backId+'\' ';

    	//(NotActive__c = true or (RecordType.DeveloperName like \'%Adjust%\' and NotActive__c != true )) 
    	List<SalesPerformanceDataSheet__c> sdlist = Database.query(sql);


    	Set<String> spIds = new Set<String>();
    	List<String> details  = new List<String>();

	    List<PerformanceBean> adjustList = new List<PerformanceBean>();
	    //调整数据 
    	for (SalesPerformanceDataSheet__c  sp :sdlist ) {
    		PerformanceBean p = new PerformanceBean(sp);
    		
    		String targetRt = recordMap.get(sp.RecordType.DeveloperName);//原数据记录类型
    		List<PerformanceBean> tmp = res.containsKey(targetRt) ? res.get(targetRt) : new List<PerformanceBean>();
			tmp.add(p);    

			res.put(targetRt,tmp);

    		spIds.add(sp.SalesPerformanceDataSheet__c);
    		details.add(sp.Id);


    	}
    	Map<String,PerformanceBean> temMap = new Map<String,PerformanceBean>();
    	
    	if(!spIds.isEmpty()){

    		//NC
    		System.debug('historysql=> '+historysql + ' and Id in (\''+String.join(new List<String>(spIds), '\',\'')+'\') ');
    		for(SalesPerformanceDataSheet__c sp : Database.query(historysql + ' where  Id in (\''+String.join(new List<String>(spIds), '\',\'')+'\') ') ){
	    		PerformanceBean p = new PerformanceBean(sp);
	    		String targetRt = p.recordType;
	    		
	    		List<PerformanceBean> tmp = res.containsKey(targetRt) ? res.get(targetRt) : new List<PerformanceBean>();
	    		temMap.put(sp.Id, p);
	    		tmp.add(p);
				res.put(targetRt,tmp);


	    	}


	    	//历史调整
	    	for(SalesPerformanceDataSheet__c sp : Database.query(historysql + ' where SalesPerformanceDataSheet__c in (\''+String.join(new List<String>(spIds), '\',\'')+'\') and  Id not in (\''+String.join(details, '\',\'')+'\') and  SalesPerformanceAdjustment__r.Status__c =\'审批成功\' order by LastModifiedDate desc  ') ){

	    		PerformanceBean pb = temMap.get(sp.SalesPerformanceDataSheet__c );
				if(pb == null)continue;
				if(pb.historys != null && pb.historys.size() > 0 )continue;
				pb.historys =  pb.historys == null ? new List<PerformanceBean>() : pb.historys;
				pb.historys.add(new PerformanceBean(sp));


	    	}



    	}
    	
    	
    	return res ; 
    

    }


    public class PerformanceBean{

    	public String detailId ;//记录Id;

    	public String company ; //归口公司
    	public String name;

    	public String province ;//归口省份
    	public String accName ;
    	public String accId ;
    	public String accpk;

    	public String terminalName;
    	public String terminalId;
    	public String terminalpk;

    	public Decimal tn1;//1季度仪器目标数量
    	public Decimal tn2;
    	public Decimal tn3;
    	public Decimal tn4;

    	public Decimal an1;//1季度仪器安装数量
    	public Decimal an2;
    	public Decimal an3;
    	public Decimal an4;

    	public Decimal ls1;//去年1季度销售目标
    	public Decimal ls2;
    	public Decimal ls3;
    	public Decimal ls4;

    	public Decimal ts1;//1季度销售目标
    	public Decimal ts2;
    	public Decimal ts3;
    	public Decimal ts4;

    	public Decimal as1;//1季度销售
    	public Decimal as2;
    	public Decimal as3;
    	public Decimal as4;

    	public String cate ;//类别
    	public String equipCate; //仪器类别
    	public String regentCate; //试剂类别
    	public String increaCate; //增量类别


    	public String saleMarket ; 

    	public String recordType ;
    	public String relatedId;

    	public String year;
    	public String quater;
    	public String jobclass;
    	public String reason;

    	public  List<PerformanceBean> historys ;

    	public PerformanceBean( SalesPerformanceDataSheet__c sp ){
    		quater = sp.Quarter__c;
    		year = sp.Year__c;
    		jobclass = sp.JobCategory__c;
    		name = sp.Name__c;

    		detailId = sp.Id;
    		relatedId = sp.SalesPerformanceDataSheet__c;
    		company = sp.Company__c;
    		province = sp.Province__c;
    		accName = sp.Account__r.Name;
    		accpk = sp.AccountPK__c;
    		accId = sp.Account__c;
    		reason = sp.Reason__c;
    		saleMarket = sp.SalesMarket__c;

    		terminalId = sp.TerminalAccount__c;
    		terminalpk = sp.TerminalAccountPK__c;
    		terminalName = sp.TerminalAccount__r.Name;

    		tn1 = sp.BudgetQuantityQ1__c;
    		tn2 = sp.BudgetQuantityQ2__c;
    		tn3 = sp.BudgetQuantityQ3__c;
    		tn4 = sp.BudgetQuantityQ4__c;

    		an1 = sp.ActualQuantityQ1__c;
    		an2 = sp.ActualQuantityQ2__c;
    		an3 = sp.ActualQuantityQ3__c;
    		an4 = sp.ActualQuantityQ4__c;

    		ls1 = sp.LastYearSalesVolumeQ1__c;
    		ls2 = sp.LastYearSalesVolumeQ2__c;
    		ls3 = sp.LastYearSalesVolumeQ3__c;
    		ls4 = sp.LastYearSalesVolumeQ4__c;

    		ts1 = sp.BudgetSalesQ1__c;
    		ts2 = sp.BudgetSalesQ2__c;
    		ts3 = sp.BudgetSalesQ3__c;
    		ts4 = sp.BudgetSalesQ4__c;

    		as1 = sp.ActualSalesQ1__c;
    		as2 = sp.ActualSalesQ2__c;
    		as3 = sp.ActualSalesQ3__c;
    		as4 = sp.ActualSalesQ4__c;

    		cate = sp.Category__c;
    		equipCate = sp.InstrumentClasses__c;
    		regentCate = sp.ReagentCategory__c;
    		increaCate = sp.IncrementalCcategory__c;

    		recordType = sp.RecordType.DeveloperName;


    	}


    }




}